package com.pn.interceptors;

import com.pn.utils.JwtUtil;
import com.pn.utils.ThreadLocalUtil;
import com.pn.utils.WarehouseConstants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements  HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证,从浏览器的请求头中获取令牌
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        log.info("验证令牌:{}",token);
        try {
            //验证token
            //从redis中获取相同的token
            String redistToken = stringRedisTemplate.opsForValue().get(token);
            if(redistToken == null){
                throw new RuntimeException("令牌过期");
            }

            Map<String, Object> claims = JwtUtil.parseToken(token);

            ThreadLocalUtil.set(claims);

            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }


}
